package com.koron.dynamic.dataSource;

import org.aspectj.lang.ProceedingJoinPoint;

/**
 * @ClassName DataSourceAspect
 * @description
 * @Author zhouj
 * @Date 2021/7/14 15:50
 */
//@Slf4j
//@Aspect
//@Order(-1)// 该切面应当先于 @Transactional 执行
//@Component
public class DataSourceAspect{

    /*@Pointcut("@annotation(com.koron.*.DS)")
    public void dataSourcePointCut() {

    };

    @Before("dataSourcePointCut()")
    public void switchDataSource(JoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        DS ds = method.getAnnotation(DS.class);
        if(ds != null){
            DynamicDataSourceContextHolder.setDataSourceKey(ds.name());
            log.debug("set datasource is " + ds.name());
        }else {
            log.debug("set datasource is " + DynamicDataSourceContextHolder.getDataSourceKey());
        }
    }

    @After("dataSourcePointCut()")
    public void restoreDataSource(JoinPoint point) {
        // 将数据源置为默认数据源
        DynamicDataSourceContextHolder.clearDataSourceKey();
    }*/

    //@Around("execution(* com.koron.*.*.controller.*.*(..)) ")
    public Object doAround(ProceedingJoinPoint jp) throws Throwable {
        String dataSourceKey = DynamicDataSourceContextHolder.getDataSourceKey();
        //log.info("当前租户dataSourceKey:{}", dataSourceKey);
        //DynamicDataSourceContextHolder.setDataSourceKey(tenantId);
        Object result = jp.proceed();
        DynamicDataSourceContextHolder.clearDataSourceKey();
        return result;
    }

}
